package com.gange.mybatis.service.impl;

import com.gange.mybatis.dao.EmpDao;
import com.gange.mybatis.entity.Emp;
import com.gange.mybatis.service.EmpService;
import com.gange.mybatis.utils.MybatisUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class EmpServiceImpl implements EmpService {
    @Override
    public void deleteById(int id) {

        SqlSession session = MybatisUtils.getSession();
        System.out.println("delete方法里面的session："+session);
        //业务操作
        EmpDao empDao = session.getMapper(EmpDao.class);
        empDao.deleteById(id);

        session.commit();
    }

    @Override
    public void saveEmp(Emp emp) {

        SqlSession session = MybatisUtils.getSession();
        System.out.println("save方法里面的session："+session);
        //业务操作
        EmpDao empDao = session.getMapper(EmpDao.class);
        empDao.insertEmp(emp);
        session.commit();

    }

    @Override
    public void deleteAndSave(int id, Emp emp) {
//        SqlSession session = MybatisUtils.getSession();
//        //业务操作
//        EmpDao empDao = session.getMapper(EmpDao.class);
//        empDao.insertEmp(emp);
//        empDao.deleteById(id);
//        session.commit();
//        MybatisUtils.closeSession(session);


        //这样使用会创建两个session对象
        SqlSession session = MybatisUtils.getSession();
        System.out.println(session);
        try {
            saveEmp(emp);
            deleteById(id);
        }catch (Exception e){
            session.rollback();
        }
        session.commit();
        MybatisUtils.closeSession();
    }
}
